package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter , Ordered {

    private final String AUTHORIZE_TOKEN = "token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("AuthorizeFilter execute ...");
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //如果是登录操作,放行. /admin/login
        if(request.getURI().getPath().contains("/admin/login")){
            //放行
            return chain.filter(exchange);
        }
        //获取请求头,token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(AUTHORIZE_TOKEN);
        //验证,是否有令牌(token)
        if(StringUtils.isEmpty(token)) {
            //没有令牌,则没有权限访问,返回状态码401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //如果有令牌,解析令牌
            //如果后续需要验证权限等操作,可以解析claims对象,得到json数组中的属性,进行校验比对
            Claims claims = JwtUtil.parseJWT(token);
            System.out.println("claims : "+claims);
            //解析成功,权限认证没问题,放行.
            return chain.filter(exchange);
        }catch (Exception e){
            e.printStackTrace();
            //解析失败,无权限执行
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
